package com.hyphenate.easeui.mwidget;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Picture;
import android.graphics.Rect;
import android.graphics.RectF;
import android.net.Uri;
import android.os.Build;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import java.util.ArrayList;
import java.util.List;

public class MWebView extends WebView {
    WebFunction webFunction;

    public MWebView(Context context) {
        super( context );
        initWebConf();
    }

    public MWebView(Context context, AttributeSet attrs) {
        super( context, attrs );
        initWebConf();
    }

    public MWebView(Context context, AttributeSet attrs, int defStyleAttr) {
        super( context, attrs, defStyleAttr );
        initWebConf();
    }
    public void setWebFunction(WebFunction webFunction) {
        this.webFunction = webFunction;
    }

    String bilibili1 = "<!DOCTYPE HTML>\n" +
            "<html>\n" +
            "    \n" +
            "    <head>\n" +
            "\n" +
            "    <style type=\"text/css\">\n" +
            "        .aspect-ratio {\n" +
            "            position: relative;\n" +
            "            width: 100%;\n" +
            "            height: 0;\n" +
            "            padding-bottom: 75%;\n" +
            "        }\n" +
            "    \n" +
            "    .aspect-ratio iframe {\n" +
            "        position: absolute;\n" +
            "        width: 100%;\n" +
            "        height: 100%;\n" +
            "        left: 0;\n" +
            "        top: 0;\n" +
            "    }\n" +
            "    </style>\n" +
            "    \n" +
            "        \n" +
            "    </head>\n" +
            "    \n" +
            "    <body>\n" +
            "        \n" +
            "        <h1> test </h1>\n" +
            "        \n" +
            "        <div class=\"aspect-ratio\" >\n" +
            "            <iframe src=\"";
    String bilibili2 = "\" scrolling=\"no\" border=\"0\" frameborder=\"no\" framespacing=\"0\" allowfullscreen=\"true\"> </iframe>\n" +
            "        </div>\n" +
            "        \n" +
            "    </body>\n" +
            "</html>\n";


    protected void initWebConf() {
        setDrawingCacheEnabled( true );
        WebSettings webSettings = getSettings();

//如果访问的页面中要与Javascript交互，则webview必须设置支持Javascript
        webSettings.setJavaScriptEnabled( true );
// 若加载的 html 里有JS 在执行动画等操作，会造成资源浪费（CPU、电量）
// 在 onStop 和 onResume 里分别把 setJavaScriptEnabled() 给设置成 false 和 true 即可

//支持插件
//        webSettings.setPluginsEnabled(true);

//设置自适应屏幕，两者合用
        webSettings.setUseWideViewPort( true ); //将图片调整到适合webview的大小
        webSettings.setLoadWithOverviewMode( true ); // 缩放至屏幕的大小

//缩放操作
        webSettings.setSupportZoom( true ); //支持缩放，默认为true。是下面那个的前提。
        webSettings.setBuiltInZoomControls( true ); //设置内置的缩放控件。若为false，则该WebView不可缩放
        webSettings.setDisplayZoomControls( false ); //隐藏原生的缩放控件

//其他细节操作
        webSettings.setCacheMode( WebSettings.LOAD_CACHE_ELSE_NETWORK ); //关闭webview中缓存
        webSettings.setAllowFileAccess( true ); //设置可以访问文件
        webSettings.setJavaScriptCanOpenWindowsAutomatically( true ); //支持通过JS打开新窗口
        webSettings.setLoadsImagesAutomatically( true ); //支持自动加载图片
        webSettings.setDefaultTextEncodingName( "utf-8" );//设置编码格式
//        setInitialScale( 175 );
        webSettings.setTextZoom( 175 );

        // 启用javascript
        webSettings.setJavaScriptEnabled( true );
        // 开启支持视频
        webSettings.setPluginState( WebSettings.PluginState.ON );
        webSettings.setJavaScriptCanOpenWindowsAutomatically( true );
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webSettings.setMixedContentMode( WebSettings.MIXED_CONTENT_ALWAYS_ALLOW );
            webSettings.setMediaPlaybackRequiresUserGesture( false );
        }
        //优先使用缓存:
//        getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        //缓存模式如下：
        //LOAD_CACHE_ONLY: 不使用网络，只读取本地缓存数据
        //LOAD_DEFAULT: （默认）根据cache-control决定是否从网络上取数据。
        //LOAD_NO_CACHE: 不使用缓存，只从网络获取数据.
        //LOAD_CACHE_ELSE_NETWORK，只要本地有，无论是否过期，或者no-cache，都使用缓存中的数据。

        //不使用缓存:
        getSettings().setCacheMode( WebSettings.LOAD_NO_CACHE );
        setWebViewClient( new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                        webFunction.goNewWebUrl( url );
//                if (url.startsWith( "https://player.bilibili.com" )) {
//                    Uri uri = Uri.parse(url);
//                    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
//                    getContext().startActivity(intent);
////
//                    return true;
//                }
//                if (url.startsWith( "https://www.bilibili.com" )) {
//                    if (webFunction != null)
//                    return true;
//                }
//                if (url.startsWith( "bilibili:" )) {
//                return true;
//                }
//                    view.loadUrl( url );
                return true;
            }

            @Override
            public void onScaleChanged(WebView view, float oldScale, float newScale) {
//                if (DebugLog.isDebug) {
//                    DebugLog.d(TAG, "onScaleChanged oldScale = " + oldScale +"; newScale = " +newScale);
//                }
//                if (newScale - oldScale > 0.5 || newScale - oldScale < -0.5) {
//                    view.setInitialScale( (int) (oldScale / newScale * 100) ); //异常放大，缩回去。
//                }
            }
        } );

    }

    public interface WebFunction {
        void goNewWeb(String string);
        void goNewWebUrl(String url);
    }

    public Bitmap captureWebView() {
        //1:发起测量
        measure( 0, 0 );
//2:获取测量后高度 == Webview的高度
        int contentHeight = getMeasuredHeight();
//3:获取Webview控件的高度
        int height = getHeight();
//4:计算滚动次数
        int totalScrollCount = contentHeight / height;
//5: 剩余高度
        int surplusScrollHeight = contentHeight - (totalScrollCount * height);

//存储图片容器
        List<Bitmap> cacheBitmaps = new ArrayList<>();
        for (int i = 0; i < totalScrollCount; i++) {
            if (i > 0) {
                //滚动WebView
                setScrollY( i * height );
            }
            //获取截图,通过步骤1获取,这里不贴代码了
            Bitmap bitmap = getScreenshot();
            cacheBitmaps.add( bitmap );
        }

//如果不能整除,需要额外滚动1次
        if (surplusScrollHeight > 0) {
            setScrollY( contentHeight );
            Bitmap bitmap = getScreenshot();
            cacheBitmaps.add( bitmap );
        }
        return mergeBitmap( cacheBitmaps );
//        Bitmap bitmap = getDrawingCache();
//        return bitmap;
    }

    private Bitmap getScreenshot() {
        //1:打开缓存开关
        setDrawingCacheEnabled( true );
//2:获取缓存
        Bitmap drawingCache = getDrawingCache();
//3:拷贝图片(这里就是我们需要的截图内容啦)
        Bitmap newBitmap = Bitmap.createBitmap( drawingCache );
//4:关闭缓存开关
        setDrawingCacheEnabled( false );
        return newBitmap;
    }

    public Bitmap mergeBitmap(List<Bitmap> datas) {
        int contentHeight = getMeasuredHeight();
//3:获取Webview控件的高度
        int height = getHeight();
//4:计算滚动次数
        int totalScrollCount = contentHeight / height;
//5: 剩余高度
        int surplusScrollHeight = contentHeight - (totalScrollCount * height);

        //图纸宽度(因为是截图,图片宽度大小都是一样的)
        int bitmapWidth = datas.get( 0 ).getWidth();
        //图纸高度 = WebView内容的高度
        int bitmapHeight = getMeasuredHeight();
        //1:创建图纸
        Bitmap bimap = Bitmap.createBitmap( bitmapWidth, bitmapHeight, Bitmap.Config.RGB_565 );
        //2:创建画布,并绑定图纸
        Canvas canvas = new Canvas( bimap );
        //3:创建画笔
        Paint paint = new Paint();
        for (int count = datas.size(), i = 0; i < count; i++) {
            Bitmap data = datas.get( i );
            float left = 0;
            float top = i * data.getHeight();
            Rect src = null;
            RectF des = null;
            /**
             * Rect src = new Rect(); 代表图片矩形范围
             * RectF des = new RectF(); 代表Canvas的矩形范围(显示位置)
             */
            if (i == count - 1 && surplusScrollHeight > 0) {
                int srcRectTop = data.getHeight() - surplusScrollHeight;
                src = new Rect( 0, srcRectTop, data.getWidth(), data.getHeight() );
                des = new RectF( left, top, data.getWidth(), top + surplusScrollHeight );
            } else {
                src = new Rect( 0, 0, data.getWidth(), data.getHeight() );
                des = new RectF( left, top, data.getWidth(), top + data.getHeight() );
            }
            //绘制图片
            canvas.drawBitmap( data, src, des, paint );
        }
        return bimap;
    }

//        try {
//            String fileName = Environment.getExternalStorageDirectory().getPath() + "/webview_jietu.jpg";
//            FileOutputStream fos = new FileOutputStream(fileName);
//            //压缩bitmap到输出流中
//            bitmap.compress(Bitmap.CompressFormat.JPEG, 70, fos);
//            bitmap.recycle();
//            fos.close();
//            Toast.makeText(WebviewFromDrawCache.this, "截屏成功", Toast.LENGTH_LONG).show();
//
//        } catch (Exception e) {
//            Log.e(TAG, e.getMessage());
//        } finally {
//            bitmap.recycle();
//        }
//
//            measure(View.MeasureSpec.makeMeasureSpec(
//                    View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED),
//                    View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
//            layout(0, 0, getMeasuredWidth(),
//                    getMeasuredHeight());
//            setDrawingCacheEnabled(true);
//            buildDrawingCache();
//
//            Bitmap bm = Bitmap.createBitmap(getMeasuredWidth(),
//                    getMeasuredHeight(), Bitmap.Config.RGB_565);
//
//            Canvas bigcanvas = new Canvas(bm);
//            Paint paint = new Paint();
//            int iHeight = bm.getHeight();
//            bigcanvas.drawBitmap(bm, 0, iHeight, paint);
//            draw(bigcanvas);
//            return  bm;
//    }
}
